package com.project.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.project.entity.User;
import com.project.service.UserService;

public class LoginServlet extends HttpServlet {

	
	private static final long serialVersionUID = 1L;


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String name = request.getParameter("username");
		String password = request.getParameter("password");
		
		if(name == null || "".equals(name) || password == null || "".equals(password)) {
			response.sendRedirect("login.jspx?code=10002");
			return;
		}
		UserService service = new UserService();
		User user = service.findByName(name);
		
		if(user != null && user.getPassword().equals(password)) {			
			request.getSession().setAttribute("user", user);		
			response.sendRedirect("main.jspx");
		} else {
			response.sendRedirect("login.jspx?code=10001");
		}
	}

}
